package com.zengqingfa.springboot.redis;

import com.alibaba.fastjson.JSON;
import com.zengqingfa.springboot.redis.constants.RedisCacheKeyConstants;
import com.zengqingfa.springboot.redis.entity.User;
import com.zengqingfa.springboot.redis.mapper.UserMapper;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;

/**
 * @fileName: SpringRedisDemoApplication
 * @author: zengqf3
 * @date: 2020-12-30 19:42
 * @description:
 */
@SpringBootApplication
@EnableCaching
public class SpringRedisDemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringRedisDemoApplication.class);
    }


    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //新建一个Jackson2JsonRedis的redis存储的序列化方式
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //解决查询缓存转换异常的问题
        // 配置序列化（解决乱码的问题）
        //entryTtl设置过期时间
        //serializeValuesWith设置redis存储的序列化方式
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                //设置缓存失效时间
                .entryTtl(Duration.ofDays(2))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer))
                .disableCachingNullValues();
        //定义要返回的redis缓存管理对象
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) throws Exception {
//        List<User> users = userMapper.selectList(null);
//        users.forEach(user -> {
//            redisTemplate.opsForValue().set(RedisCacheKeyConstants.USER_INFO_ID + user.getId(), JSON.toJSONString(user));
//        });
    }
}
